import { app, protocol, BrowserWindow, Menu, ipcMain, Tray, nativeImage, desktopCapturer, screen } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'
import path from 'path'
import os from 'os'
import robot from 'robotjs'

protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }])

// 帮助
ipcMain.on('opennew', (event, data) => {
    let smWin = new BrowserWindow({
        center: true,
        width: 400,
        height: 400,
        resizable: false,
        maximizable: true,
        autoHideMenuBar: true,
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            preload: path.join(__dirname, 'preload.js')
        }
    })
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        smWin.loadURL(
            process.env.WEBPACK_DEV_SERVER_URL + '#/' + data + '?platform=' + process.platform + '&arch=' + process.arch
        )
    } else {
        smWin.loadURL('app://./index.html#/' + data + '?platform=' + process.platform + '&arch=' + process.arch)
    }
    event.returnValue = 'pong'
})

ipcMain.on('createRemoteWindow', (event, data) => {
    createRemoteWindow(data)
    event.returnValue = 'pong'
})

ipcMain.on('createAnswerWindow', (event, data) => {
    createAnswerWindow(data)
    event.returnValue = 'pong'
})

ipcMain.handle('getSize', event => {
    const { size } = screen.getPrimaryDisplay()
    return { width: size.width, height: size.height }
})

ipcMain.handle('getScreenStream', async event => {
    let sources = await desktopCapturer.getSources({ types: ['screen', 'window'] })
    return sources
})

ipcMain.on('robot', (event, data) => {
    if (data.type === 'mouse') {
        if (data.action === 'move') {
            // 移动鼠标
            robot.moveMouse(data.x, data.y)
        } else if (data.action === 'smooth') {
            // 移动鼠标
            robot.moveMouseSmooth(data.x, data.y)
        } else if (data.action === 'click') {
            // 点击鼠标左键
            robot.mouseClick(data.button, data.double)
        } else if (data.action === 'toggle') {
            // 按下鼠标右键
            robot.mouseToggle(data.down, data.button)
        } else if (data.action === 'drag') {
            // 拖拽
            robot.dragMouse(data.x, data.y)
        } else if (data.action === 'scroll') {
            robot.scrollMouse(data.x, data.y)
        }
    } else if (data.type === 'keyboard') {
        if (data.action === 'tap') {
            // 按下和松开键
            if (data.modifier) {
                robot.keyTap(data.key, data.modifier)
            } else {
                robot.keyTap(data.key)
            }
        } else if (data.action === 'toggle') {
            // 按下按键并保持不松开
            robot.keyToggle(data.key, data.down, data.modifier)
        } else if (data.action === 'string') {
            // 输入字符串
            robot.typeString(data.string)
        }
    }
})

ipcMain.on('closeRemote', event => {
    remoteWindow.destroy()
    event.returnValue = 'pong'
})

ipcMain.on('closeAnswer', event => {
    answerWindow.destroy()
    event.returnValue = 'pong'
})

ipcMain.handle('getDeviceInfo', event => {
    return { hostname: os.hostname(), platform: process.platform, version: os.release(), arch: process.arch }
})

let mainWindow = null
let remoteWindow = null
let answerWindow = null

async function createMainWindow() {
    // 禁止程序多开
    if (!app.requestSingleInstanceLock()) {
        app.quit()
        return
    }

    mainWindow = new BrowserWindow({
        center: true,
        width: 680,
        height: 450,
        resizable: false,
        maximizable: false,
        autoHideMenuBar: true,
        useContentSize: true,
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            preload: path.join(__dirname, 'preload.js')
        }
    })

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
    } else {
        createProtocol('app')
        mainWindow.loadURL('app://./index.html')
    }

    // 隐藏任务栏
    mainWindow.on('close', event => {
        if (process.platform !== 'darwin') {
            mainWindow.hide() // 隐藏主程序窗口
            mainWindow.setSkipTaskbar(true) // 取消任务栏显示
            event.preventDefault() // 阻止退出程序
        } else {
            // mainWindow.hide()
            // event.preventDefault()
        }
    })

    const appIcon = createTray()

    // 点击任务栏
    mainWindow.on('focus', () => {
        if (process.platform !== 'darwin') {
            appIcon.setImage(nativeImage.createFromPath(path.join(__static + '/trayTemplate.png')))
            mainWindow.flashFrame(false)
        } else {
            app.dock.setBadge('')
        }
    })
}

async function createRemoteWindow(data) {
    const { size } = screen.getPrimaryDisplay()
    let width = parseInt(size.width * (660 / size.height))
    let height = 660
    remoteWindow = new BrowserWindow({
        center: true,
        width,
        height,
        autoHideMenuBar: true,
        useContentSize: true,
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            preload: path.join(__dirname, 'preload.js')
        }
    })
    remoteWindow.on('resize', () => {
        const { width, height } = remoteWindow.getContentBounds()
        remoteWindow.webContents.send('resize', width, height)
    })
    remoteWindow.on('close', () => {
        if (!remoteWindow.isDestroyed()) {
            remoteWindow.webContents.send('close')
        }
    })
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        await remoteWindow.loadURL(
            process.env.WEBPACK_DEV_SERVER_URL +
                '#/offer?width=' +
                width +
                '&height=' +
                height +
                '&from=' +
                data.from +
                '&to=' +
                data.to +
                '&mark=' +
                data.mark
        )
        if (!process.env.IS_TEST) remoteWindow.webContents.openDevTools()
    } else {
        remoteWindow.loadURL(
            'app://./index.html#/offer?width=' +
                width +
                '&height=' +
                height +
                '&from=' +
                data.from +
                '&to=' +
                data.to +
                '&mark=' +
                data.mark
        )
    }
}

async function createAnswerWindow(data) {
    const { workAreaSize } = screen.getPrimaryDisplay()
    answerWindow = new BrowserWindow({
        width: 380,
        height: 120,
        x: workAreaSize.width - 380,
        y: workAreaSize.height - 120,
        frame: false,
        alwaysOnTop: true,
        useContentSize: true,
        resizable: false,
        autoHideMenuBar: true,
        type: 'toolbar',
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            preload: path.join(__dirname, 'preload.js')
        }
    })
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        await answerWindow.loadURL(
            process.env.WEBPACK_DEV_SERVER_URL + '#/answer?from=' + data.from + '&to=' + data.to + '&mark=' + data.mark
        )
        if (!process.env.IS_TEST) answerWindow.webContents.openDevTools()
    } else {
        answerWindow.loadURL('app://./index.html#/answer?from=' + data.from + '&to=' + data.to + '&mark=' + data.mark)
    }
}

/**
 * 创建托盘图标
 */
function createTray() {
    // 托盘
    const appIcon = new Tray(nativeImage.createFromPath(path.join(__static + '/trayTemplate.png')))
    const contextMenu = Menu.buildFromTemplate([
        {
            label: '退出',
            click: () => {
                app.exit()
            }
        }
    ])
    appIcon.setToolTip('BitDesk')
    appIcon.setContextMenu(contextMenu)
    appIcon.on('click', function () {
        showMain(appIcon, '/trayTemplate.png')
    })

    return appIcon
}

/**
 * 展示窗口，打开任务栏
 */
function showMain(appIcon) {
    mainWindow.setSkipTaskbar(false)
    mainWindow.show()
    appIcon.setImage(nativeImage.createFromPath(path.join(__static + '/trayTemplate.png')))
}

// 当运行第二个实例时，将会聚焦到win这个窗口
app.on('second-instance', () => {
    if (mainWindow) {
        if (mainWindow.isMinimized()) mainWindow.restore()
        if (mainWindow.isVisible()) {
            mainWindow.focus()
        } else {
            mainWindow.show()
            mainWindow.setSkipTaskbar(false)
        }
    }
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createMainWindow()
    } else {
        mainWindow.show()
    }
})

app.on('ready', async () => {
    await createMainWindow()
})

if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', data => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}
